package tn.orange.canreminder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import tn.orange.canreminder.adapter.PlaceAdapter;
import tn.orange.canreminder.exception.LocationNotFoundException;
import tn.orange.canreminder.location.MyLocation;
import tn.orange.canreminder.location.MyLocation.LocationResult;
import tn.orange.canreminder.model.Gps;
import tn.orange.canreminder.model.Place;
import tn.orange.canreminder.service.PlaceService;
import tn.orange.canreminder.service.PlaceServiceImp;
import tn.orange.canreminder.sort.PlaceDistanceComparator;
import tn.orange.canreminder.sort.PlaceNoteComparator;
import tn.orange.canreminder.sqlite.PlaceDao;
import tn.orange.canreminder.sqlite.PlaceDaoImp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;

public class ListPlaceActivity extends Activity implements LocationListener {

	private ListView listView;
	private LocationManager lManager;
	private Location location;
	private int category_id;
	private boolean value = false;
	private List<Place> places = new ArrayList<Place>();

	private static final int ID_AVIS = 1;
	private static final int ID_MAP = 2;
	private static final int ID_TEL = 3;
	private static final int ID_FAV = 4;
	private int posPlace;

	private Button distanceBtn;
	private Button noteBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.places);
		category_id = getIntent().getExtras().getInt("category_id");
		listView = (ListView) findViewById(R.id.list_places);
		distanceBtn = (Button) findViewById(R.id.places_btn_distance);
		distanceBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PlaceDistanceComparator comparator = new PlaceDistanceComparator();
				Collections.sort(places, comparator);

				listView.setAdapter(new PlaceAdapter(ListPlaceActivity.this,
						places, location));
			}
		});
		// distanceBtn.setOnClickListener(this);
		noteBtn = (Button) findViewById(R.id.places_btn_note);
		noteBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PlaceNoteComparator comparator = new PlaceNoteComparator();
				Collections.sort(places, comparator);

				listView.setAdapter(new PlaceAdapter(ListPlaceActivity.this,
						places, location));
			}
		});
		// noteBtn.setOnClickListener(this);
		LocationResult locationResult = new LocationResult() {

			@Override
			public void gotLocation(Location location1) {
				// TODO Auto-generated method stub
				location = location1;
			}
		};

		MyLocation myLocation = new MyLocation();

		myLocation.getLocation(ListPlaceActivity.this, locationResult);
		PlaceAsyncTask asyncTask = new PlaceAsyncTask();
		asyncTask.execute(location);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ListPlaceActivity.this,
						OpinionActivity.class);
				startActivity(intent);

			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 200) {
			PlaceAsyncTask asyncTask = new PlaceAsyncTask();
			asyncTask.execute(location);

		}
	}

	private class PlaceAsyncTask extends AsyncTask<Location, Void, List<Place>> {

		private int error;
		private final ProgressDialog dialog = new ProgressDialog(
				ListPlaceActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();

		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Place> doInBackground(final Location... args) {

			List<Place> places = new ArrayList<Place>();
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {

				PlaceService service = new PlaceServiceImp();
				if (location == null)
					throw new LocationNotFoundException();
				Gps gps = new Gps();
				gps.setLatitude(location.getLatitude());
				gps.setLongitude(location.getLongitude());
				gps.setRayon(10000000);
				gps.setCategory_id(category_id);
				places = service.sendGPS(gps);
				// places = MockObject.getMockPlaces();

			} catch (LocationNotFoundException e) {
				// TODO Auto-generated catch block
				error = 1;
				cancel(false);
			} catch (Exception e) {
				// TODO: handle exception
			}
			return places;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {

				this.dialog.dismiss();
			}
			if (error == 1) {
				showErrorDialog("problème de localisation GPS");

			} else
				showErrorDialog("Problème de connexion ");

		}

		// can use UI thread here
		protected void onPostExecute(final List<Place> myplaces) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();

			}
			places = myplaces;

			for (Place place : places) {
				Location placeLocation = new Location("gps");
				placeLocation.setLatitude(place.getLongitude());
				placeLocation.setLongitude(place.getLatitude());
				String distance = "" + location.distanceTo(placeLocation);
				int pos = distance.indexOf(".");
				distance = distance.substring(0, pos + 2);
				place.setDistance(Double.parseDouble(distance));
			}

			PlaceDistanceComparator comparator = new PlaceDistanceComparator();
			Collections.sort(places, comparator);

			listView.setAdapter(new PlaceAdapter(ListPlaceActivity.this,
					places, location));

		}

		private void showErrorDialog(String message) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					ListPlaceActivity.this).create();
			alertDialog.setTitle("Erreur");
			alertDialog.setMessage(message);
			alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					ListPlaceActivity.this.finish();
				}
			});

			alertDialog.show();
		}
	}

	public void onLocationChanged(Location location) {

		this.location = location;

		lManager.removeUpdates(this);
		PlaceAsyncTask asyncTask = new PlaceAsyncTask();
		asyncTask.execute(location);

	}

	public void onProviderDisabled(String provider) {

		lManager.removeUpdates(this);

	}

	public void onProviderEnabled(String provider) {
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	//
	// if (v == distanceBtn) {
	// PlaceDistanceComparator comparator = new PlaceDistanceComparator();
	// Collections.sort(places, comparator);
	//
	// listView.setAdapter(new PlaceAdapter(ListPlaceActivity.this,
	// places, location));
	//
	// } else if (v == noteBtn) {
	// PlaceNoteComparator comparator = new PlaceNoteComparator();
	// Collections.sort(places, comparator);
	//
	// listView.setAdapter(new PlaceAdapter(ListPlaceActivity.this,
	// places, location));
	// }
	//
	// }

	public void OnClickOpinion(View v) {
		Intent intent = new Intent(ListPlaceActivity.this,
				OpinionActivity.class);
		int position = (Integer) v.getTag();
		intent.putExtra("place_id", position);
		startActivityForResult(intent, 1);
	}

	public void OnClickMap(View v) throws IOException {

		int position = (Integer) v.getTag();
		Place place = places.get(position);

		Intent intent1 = new Intent(android.content.Intent.ACTION_VIEW,
				Uri.parse("http://maps.google.com/?saddr="
						+ location.getLatitude() + ","
						+ location.getLongitude() + "&daddr="
						+ place.getLongitude() + "," + place.getLatitude()));
		startActivity(intent1);

	}

	public void OnFavClick(View v) {
		CheckBox box = (CheckBox) v;
		if (box.isChecked()) {
			PlaceDao placeDao = new PlaceDaoImp(ListPlaceActivity.this);
			Place place = places.get((Integer) v.getTag());

			tn.orange.canreminder.sqlite.Place placedb = new tn.orange.canreminder.sqlite.Place();

			placedb.setAdresse(place.getAdresse());
			placedb.setCategory(" ");
			placedb.setImage("image");
			placedb.setLatitude("" + place.getLatitude());
			placedb.setLongitude("" + place.getLongitude());
			placedb.setNom(place.getName());
			placedb.setTelephone(place.getTelephone());

			placeDao.insertPlace(placedb);
			box.setChecked(true);
		} else {
			PlaceDao placeDao = new PlaceDaoImp(getApplicationContext());
			int pos = (Integer) v.getTag();
			placeDao.deletePlace((places.get(pos).getName()));
			box.setChecked(false);

		}
	}

	public void OnHomeClick(View v) {
		Intent intent = new Intent(getApplicationContext(),
				DashboardActivity.class);
		startActivity(intent);
	}
}
